package gen.desktop.components;

import gen.core.managers.ConnConfigManager;
import gen.core.models.ConnConfig;
import gen.core.utils.GenUtils;
import gen.desktop.Application;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.util.Properties;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class ConnConfigDialog extends JDialog {
	private static final long serialVersionUID = 1L;
	private JTextField textFieldDriver;
	private JTextField textFieldUrl;
	private JTextField textFieldUser;
	private JButton buttonSave;
	private JButton buttonCancel;
	private boolean isNew;
	private JLabel label_3;
	private JTextField textFieldName;
	private JComboBox comboBox;
	private JPasswordField passwordField;
	private JButton buttonTest;

	public boolean isNew() {
		return isNew;
	}

	public void setNew(boolean isNew) {
		this.isNew = isNew;
		if (isNew == false) {
			textFieldName.setVisible(false);
			comboBox = new JComboBox();
			comboBox.setBounds(98, 10, 345, 21);
			getContentPane().add(comboBox);

			loadConnConfigListToComboBox();

			comboBox.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					if (e.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
						ConnConfig selectedConnConfig = (ConnConfig) e.getItem();
						textFieldDriver.setText(selectedConnConfig.getDriver());
						textFieldUrl.setText(selectedConnConfig.getUrl());
						textFieldUser.setText(selectedConnConfig.getUser());
						passwordField.setText(selectedConnConfig.getPassword());
					}
				}
			});

			if (comboBox.getItemCount() > 0) {
				ConnConfig firstConnConfig = (ConnConfig) comboBox.getItemAt(0);
				textFieldDriver.setText(firstConnConfig.getDriver());
				textFieldUrl.setText(firstConnConfig.getUrl());
				textFieldUser.setText(firstConnConfig.getUser());
				passwordField.setText(firstConnConfig.getPassword());
			}
		}
	}

	public ConnConfigDialog() {
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setResizable(false);
		getContentPane().setLayout(null);

		JLabel lblNewLabel = new JLabel("JDBC驱动：");
		lblNewLabel.setBounds(10, 38, 66, 15);
		getContentPane().add(lblNewLabel);

		textFieldDriver = new JTextField();
		textFieldDriver.setBounds(98, 35, 345, 21);
		getContentPane().add(textFieldDriver);
		textFieldDriver.setColumns(10);

		JLabel label = new JLabel("连接字符串：");
		label.setBounds(10, 63, 83, 15);
		getContentPane().add(label);

		JLabel label_1 = new JLabel("用户名：");
		label_1.setBounds(10, 88, 54, 15);
		getContentPane().add(label_1);

		textFieldUrl = new JTextField();
		textFieldUrl.setBounds(98, 60, 345, 21);
		getContentPane().add(textFieldUrl);
		textFieldUrl.setColumns(10);

		textFieldUser = new JTextField();
		textFieldUser.setBounds(98, 85, 345, 21);
		getContentPane().add(textFieldUser);
		textFieldUser.setColumns(10);

		JLabel label_2 = new JLabel("密码：");
		label_2.setBounds(10, 113, 54, 15);
		getContentPane().add(label_2);

		buttonSave = new JButton("保存");
		buttonSave.setBounds(170, 141, 60, 23);
		getContentPane().add(buttonSave);

		buttonCancel = new JButton("取消");
		buttonCancel.setBounds(240, 141, 60, 23);
		getContentPane().add(buttonCancel);

		label_3 = new JLabel("连接名称：");
		label_3.setBounds(10, 13, 66, 15);
		getContentPane().add(label_3);

		textFieldName = new JTextField();
		textFieldName.setBounds(98, 10, 345, 21);
		getContentPane().add(textFieldName);
		textFieldName.setColumns(10);

		passwordField = new JPasswordField();
		passwordField.setBounds(98, 110, 345, 21);
		getContentPane().add(passwordField);

		buttonTest = new JButton("测试");
		buttonTest.setBounds(383, 141, 60, 23);
		getContentPane().add(buttonTest);

		init();
	}

	private void init() {
		// 对话框的宽高
		int width = 460;
		int height = 205;

		// 居中
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		this.setBounds(((int) dim.getWidth() - width) / 2, ((int) dim.getHeight() - height) / 2, width, height);

		// 点击保存
		buttonSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ConnConfigManager aConnConfigManager = new ConnConfigManager();
				Connection conn = null;

				try {

					if (isNew) {
						// 保存数据
						conn = Application.getSqliteClient().createConnection();

						ConnConfig aConnConfig = new ConnConfig();
						aConnConfig.setName(textFieldName.getText().trim());
						aConnConfig.setCatagory("Main");
						aConnConfig.setDriver(textFieldDriver.getText().trim());
						aConnConfig.setUrl(textFieldUrl.getText().trim());
						aConnConfig.setUser(textFieldUser.getText().trim());
						aConnConfig.setPassword(new String(passwordField.getPassword()));
						aConnConfig.setOwner(Application.getOwner());
						aConnConfigManager.save(conn, aConnConfig);

						conn.commit();
					} else {
						conn = Application.getSqliteClient().createConnection();

						ConnConfig selectedConnConfig = (ConnConfig) comboBox.getSelectedItem();
						selectedConnConfig.setDriver(textFieldDriver.getText().trim());
						selectedConnConfig.setUrl(textFieldUrl.getText().trim());
						selectedConnConfig.setUser(textFieldUser.getText().trim());
						selectedConnConfig.setPassword(new String(passwordField.getPassword()));
						aConnConfigManager.save(conn, selectedConnConfig);

						conn.commit();
					}

					close();

				} catch (Exception ex) {
					ex.printStackTrace();
					JOptionPane.showMessageDialog(null, ex.getMessage(), "保存失败", JOptionPane.ERROR_MESSAGE);
					return;
				} finally {
					GenUtils.closeConnection(conn);
				}

			}
		});

		// 点击取消
		buttonCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				close();
			}
		});

		// 点击测试
		buttonTest.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Properties aProperties = new Properties();
				aProperties.setProperty("driver", textFieldDriver.getText().trim());
				aProperties.setProperty("url", textFieldUrl.getText().trim());
				aProperties.setProperty("user", textFieldUser.getText().trim());
				aProperties.setProperty("password", new String(passwordField.getPassword()).trim());

				Connection conn = null;
				try {
					GenUtils.createConnection(aProperties);
					JOptionPane.showMessageDialog(null, "测试成功！", "测试结果", JOptionPane.PLAIN_MESSAGE);
					return;
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(null, ex.getMessage(), "测试失败", JOptionPane.ERROR_MESSAGE);
					return;
				} finally {
					GenUtils.closeConnection(conn);
				}
			}
		});
	}

	private void close() {
		this.setVisible(false);
		this.dispose();
	}

	private void loadConnConfigListToComboBox() {
		ConnConfigManager aConnConfigManager = new ConnConfigManager();
		Connection conn = null;
		try {
			conn = Application.getSqliteClient().createConnection();
			ConnConfig[] ConnConfigArray = aConnConfigManager.list(conn, Application.getOwner(), "Main");
			comboBox.setModel(new DefaultComboBoxModel(ConnConfigArray));
		}catch (Exception ex) {
			ex.printStackTrace();
			JOptionPane.showMessageDialog(null, ex.getMessage(), "异常", JOptionPane.ERROR_MESSAGE);
			return;
		} finally {
			GenUtils.closeConnection(conn);
		}
	}
}
